import cv2, torch
from queue import Queue
import threading
import time

import pathlib
temp = pathlib.PosixPath
pathlib.PosixPath = pathlib.WindowsPath

def read_camera():
    model = torch.hub.load(r'./', 'custom', path=r"runs/train/exp4/weights/best.pt",
                                source="local")  # load silently)

    cap = cv2.VideoCapture(0)  # 打开默认相机 (0 代表默认相机)

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 指定视频编码器
    video_writer = cv2.VideoWriter('output.mp4', fourcc, 30.0, (int(cap.get(3)), int(cap.get(4))))  # 创建视频写入对象

    while True:
        ret, frame = cap.read()  # 读取相机帧

        if not ret:
            print("Error reading from camera")
            break

        results = model(frame)  # Inference
        image = results.show_cv()  # 获取处理后的图像

        cv2.imshow('results', image)
        video_writer.write(image)  # 写入当前帧到视频文件

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':

    recv_thread = threading.Thread(target=read_camera)
    recv_thread.daemon = True
    recv_thread.start()

    # 主线程：用于实现预定动作
    time.sleep(12)